<template>
  <!-- 使用 ref 绑定容器 -->
  <div ref="mapContainer" class="map-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watchEffect } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import modelDatas from '@/assets/json/model.json'

const route = useRoute();
const map = ref(null);
const mapContainer = ref(null); // 使用 ref 替代 ID 选择
const modelData = modelDatas.model.find((i) => i.name == route.query?.name)



const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "863c4437dcdb8702418a9d2bb4bf5562",
  };

  AMapLoader.load({
    key: "90bb4fbb23776b0c79a24889b838b412",
    version: "2.0",
    plugins: ["AMap.Scale"],
  })
    .then((AMap) => {
      // 使用 ref 的 DOM 元素
      map.value = new AMap.Map(mapContainer.value, {
        viewMode: "3D",
        zoom: 15,
        center: modelData.center,
        resizeEnable: true, // 开启自动适应
      });

      addMarker();

      // 强制刷新地图尺寸
      setTimeout(() => map.value?.resize(), 300);
    })
    .catch(console.error);
};

const addMarker = () => {
  /** 添加标记点 */
  const marker = new AMap.Marker({
    position: modelData.center,
    title: modelData.title,
  });
  map.value.add(marker);
};

// 添加延迟初始化逻辑
onMounted(() => {
  setTimeout(initMap, 500); // 延迟 500ms 确保父容器渲染完成
});

onBeforeUnmount(() => {
  map.value?.destroy();
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
}
</style>
